/*
    BibleNotebook - A bible reader software
    Copyright (C) 2014  Williams Fernando Lopez

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
 */

/*
 * NotePanel.java
 *
 * Created on 17/07/2013, 04:56:01 PM
 */

package com.simplebible.ui.components;

import wl.ui.FileViewer;
import com.simplebible.ui.components.editors.Editor;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.util.Calendar;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import com.simplebible.bible.BibleUtils;
import wl.util.TextResourcesUtil;
import wl.util.Utils;
import com.simplebible.bible.objects.Abreviation;
import com.simplebible.bible.objects.Bible;
import com.simplebible.objects.Preferences;
import com.simplebible.bible.objects.Verse;
import com.simplebible.ui.components.editors.EditorEkit;

/**
 *
 * @author Williams Lopez
 */
public class NotePanel extends javax.swing.JPanel {

    FileViewer grupos;
    Editor editor;
    File currentFileDir;
    String noteRoot = "notes";
    File dirNoteRoot;
    NewNotePopup newNotePopup = null;

    boolean showMsWordEditor = false;

    /** Creates new form NotePanel */
    public NotePanel() {
        initComponents();
        dirNoteRoot = new File(noteRoot);
        editor = new EditorEkit();
        labelRegresar.setVisible(false);
        grupos = new FileViewer();
        grupos.addFileSelectionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() != null && e.getSource() instanceof File){
                    showNote((File)e.getSource());
                }
            }
        });
        grupos.addDirectorySelectionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() != null && e.getSource() instanceof File){
                    File dir = (File)e.getSource();
                    if(!dir.getName().equals(noteRoot)){
                        showGroup(dir);
                    }
                }
            }
        });

        
        grupos.setDefaultDirectoryIcon(new ImageIcon(getClass().getResource("/simplebible/ui/img/folder_vertical_open.png")));
        grupos.setDefaultFileIcon(new ImageIcon(getClass().getResource("/simplebible/ui/img/note_edit.png")));
        currentFileDir = new File(noteRoot);
        showGroup(currentFileDir);
        labelRegresar.setVisible(false);

        try {
            TextResourcesUtil.registrarComponente(this);
        } catch (Exception e) {
        }
        

    }



    public void addVerseToNote(Bible bible, Abreviation abrv){
        Verse v = BibleUtils.findVerse(bible, abrv);
        String hn = BibleUtils.getHumanName(bible, abrv);
        editor.addTextOnCursorPosition("<a href=\"verse:"+abrv+"\">"+hn+"</a>"+" ("+bible.getHumanName()+")\n<br/>\n"+v.getTextWithoutMarks());
    }

    @Override
    public void requestFocus() {
        super.requestFocus();
        editor.requestFocusToText();
    }


    public void showNewNote() {
        showNewNote(null, null);
    }

    public void showNewNote(Bible b, Abreviation abrv) {

        final Bible fb = b;
        final Abreviation fabrv = abrv;

        if (newNotePopup == null) {
            newNotePopup = new NewNotePopup();
            newNotePopup.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    newNote(e.getActionCommand(), fb, fabrv);
                }
            });
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                newNotePopup.show(buttoNew, 0, labelAdministrar.getHeight());
            }
        });
    }


    private void newNote(String name,Bible b, Abreviation abrv){
        if(currentFileDir == null){
            currentFileDir = dirNoteRoot;
        }

        if(!currentFileDir.isDirectory()){
            currentFileDir = currentFileDir.getParentFile();
        }
        
        final Bible fb = b;
        final Abreviation fabrv = abrv;

        try {
            final File file = new File(currentFileDir.getAbsolutePath()+File.separator+name+".html");
            if(file.exists()){
                MainPanel.showYesNoCancelQuestion("nota_ya_existe", new YesNoCancelListener() {
                    public void yes(ActionEvent e) {
                        try {
                            createAndDisplayNewFile(file, fb, fabrv);
                        } catch (Exception ex) {
                            Utils.printToLog("Error al borrar o crear el archivo", ex, Preferences.LOG_LEVEL_ERROR);
                        }
                    }
                    public void no(ActionEvent e) {}
                    public void cancel(ActionEvent e) {}
                });
            }else{
                createAndDisplayNewFile(file, fb, abrv);
            }
        } catch (Exception e) {
            Utils.printToLog("Error al crear el archivo", e,Preferences.LOG_LEVEL_ERROR);
        }
    }


    private void createAndDisplayNewFile(File file, Bible bible, Abreviation abrv) throws Exception{
        String str = file.getName()+" - "+Utils.datoToString(Calendar.getInstance())+"<br/>";
        createNewFile(file, str);
        editor.open(file);
        showGroup(currentFileDir);
        if (bible != null && abrv != null) {
            addVerseToNote(bible, abrv);
        }
        showNote(file);
    }
    
    private void createNewFile(File file, String texto){
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            fileWriter.write("<html>\r\n  <head>\r\n    \r\n  </head>\r\n  <body>\r\n    <p style=\"margin-top: 0\">\r\n      "+texto+"\r\n    </p>\r\n  </body>\r\n</html>\r\n");
        } catch (Exception e) {
            Utils.printToLog("Error no puede crearse el archivo", e, Preferences.LOG_LEVEL_ERROR);
        }finally{
            if(fileWriter != null){
                try {
                    fileWriter.close();
                } catch (Exception ex) {
                }
            }
        }

    }

    public void showOpenNote(){
        if(!editor.isFileOpen()){
            return;
        }
        currentFileDir = editor.getOpenFile();
        labelRegresar.setVisible(true);
        this.jPanel2.remove(grupos);
        this.jPanel2.add(editor.getContentPane());
    }


    public void showNote(File root){
        try{
            currentFileDir = root;
            labelRegresar.setVisible(true);
            labelTitle.setText(currentFileDir.getName());
            
            this.jPanel2.remove(grupos);
            this.jPanel2.add(editor.getContentPane());
            editor.open(root);
            this.updateUI();
        }catch(Exception e){
            MainPanel.showNotification("generic_error", e);
            Utils.printToLog("Error al mostrar la nota", e,Preferences.LOG_LEVEL_ERROR);
        }
    }


    public final void showGroup(File grupo){
        try{
            currentFileDir = grupo;
            grupos.showDirectory(grupo);
            if(!grupo.getName().equals(dirNoteRoot.getName())){
                labelRegresar.setVisible(true);
            }else{
                labelRegresar.setVisible(false);
            }
            labelTitle.setText(getGroupNoteName(grupo));
            this.jPanel2.remove(editor.getContentPane());
            this.jPanel2.add(grupos);
         }catch(Exception e){
            MainPanel.showNotification("error_mostrar_notas"+e.getMessage(), e);
            Utils.printToLog("No se pueden mostrar las notas", e, ALLBITS);
        }
        this.updateUI();
    }


    public void save(){
        try {
            editor.save();
        } catch (Exception e) {
        }
    }

    public void regresar(){
        if(currentFileDir!=null && currentFileDir.getParent()!=null){
            File parent = currentFileDir.getParentFile();
            if(parent.getName().equals(noteRoot)){
                labelRegresar.setVisible(false);
            }
            this.jPanel2.remove(editor.getContentPane());
            grupos.showDirectory(parent);
            this.jPanel2.add(grupos);
            labelTitle.setText(getGroupNoteName(parent));
            currentFileDir = parent;
        }
    }

    private String getGroupNoteName(File dir){
        try{
            String s = dir.getAbsolutePath().replace(dirNoteRoot.getAbsolutePath(), "").trim();
            if(s.endsWith(".html")){
                s = s.substring(0, s.length()-5);
            }

            if(s.trim().equals("")){
                s = TextResourcesUtil.getText("notas");
            }

            return s;
        }catch(Exception e){
            return "?";
        }
    }

    public boolean isFileOpen(){
        return editor.isFileOpen();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.red);
        g.drawString("Prueba", 5, 5);
    }

    public Editor getEditor(){
        return this.editor;
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        labelAdministrar = new wl.ui.ButtonLabel();
        labelTitle = new javax.swing.JLabel();
        buttoNew = new wl.ui.ButtonLabel();
        labelRegresar = new wl.ui.ButtonLabel();
        jPanel2 = new javax.swing.JPanel();

        setBackground(new java.awt.Color(255, 255, 255));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        labelAdministrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/file_manager.png"))); // NOI18N
        labelAdministrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                labelAdministrar(evt);
            }
        });

        labelTitle.setFont(new java.awt.Font("Arial Narrow", 0, 14)); // NOI18N
        labelTitle.setForeground(new java.awt.Color(153, 153, 153));
        labelTitle.setText("-");

        buttoNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/note_add.png"))); // NOI18N
        buttoNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttoNewActionPerformed(evt);
            }
        });

        labelRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/arrow_turn_left.png"))); // NOI18N
        labelRegresar.setToolTipText("Regresar");
        labelRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                labelRegresarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttoNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelAdministrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(16, 16, 16))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelTitle, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                    .addComponent(labelRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelAdministrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttoNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.LINE_AXIS));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void labelAdministrar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelAdministrar
        try {
            Desktop.getDesktop().open(dirNoteRoot);
        } catch (Exception e) {
            MainPanel.showNotification("error_abrir_explorador_archivos", e);
            Utils.printToLog("Error al abrir el explorador de archivos", e, Preferences.LOG_LEVEL_ERROR);
        }
    }//GEN-LAST:event_labelAdministrar

    private void buttoNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttoNewActionPerformed
        showNewNote();
    }//GEN-LAST:event_buttoNewActionPerformed

    private void labelRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelRegresarActionPerformed
        regresar();
    }//GEN-LAST:event_labelRegresarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private wl.ui.ButtonLabel buttoNew;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private wl.ui.ButtonLabel labelAdministrar;
    private wl.ui.ButtonLabel labelRegresar;
    private javax.swing.JLabel labelTitle;
    // End of variables declaration//GEN-END:variables

}
